package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;

import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;

import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.log.annotation.Log;
import com.spzx.order.domain.OrderForm;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderItemService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import com.spzx.user.api.domain.UserInfo;
import com.sun.jdi.IncompatibleThreadStateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


/**
 * 订单Service业务层处理
 *
 * @author lee
 * @date 2024-07-23
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private IOrderItemService orderItemService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    private OrderLogMapper orderlogMapper;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    @Override
    public Map<String, Object> getTrade(Long userId) {
        Map<String, Object> data = new HashMap<>();

        //在缓存中获取到所有被选择的商品
        R<List<CartInfo>> checkListResult = remoteCartService.getCheckList(userId, SecurityConstants.INNER);
        if (R.FAIL == checkListResult.getCode()) {
            throw new ServiceException(checkListResult.getMsg());
        }
        List<CartInfo> checkList = checkListResult.getData();
        if (CollectionUtils.isEmpty(checkList)) {
            throw new ServiceException("购物车中没有选中的商品");
        }
        List<Long> skuIdList = new ArrayList<>();
        List<OrderItem> orderItemList = checkList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            skuIdList.add(cartInfo.getSkuId());
            return orderItem;
        }).collect(Collectors.toList());
        //获取商品实时价格
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        Map<Long, BigDecimal> skuPriceMap = skuPriceListResult.getData().stream()
                .collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        //计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(skuPriceMap.get(orderItem.getSkuId())
                    .multiply(new BigDecimal(orderItem.getSkuNum())));
            orderItem.setSkuPrice(skuPriceMap.get(orderItem.getSkuId()));
        }

        //生成tradeNo
        String tradeNo = this.generateTradeNo(userId);

        data.put("totalAmount", totalAmount);
        data.put("orderItemList", orderItemList);
        data.put("tradeNo", tradeNo);
        data.put("isBuy", false);

        return data;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        Boolean isBuy = orderForm.getIsBuy();
        //校验流水号,防止重复提交,如果缓存中有这个流水号,就将流水号删掉,如果缓存中没有这个流水号,就是重复提交
        String tradeNo = orderForm.getTradeNo();
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        Long flag = (Long) redisTemplate.execute(new DefaultRedisScript(scriptText, Long.class), Arrays.asList(userTradeKey), tradeNo);
        if (flag == 0) {
            throw new ServiceException("请勿重复提交订单，请尝试重试");
        }

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("提交的参数不合法");
        }

        //校验价格
        List<Long> skuIdList = new ArrayList<Long>();
        for (OrderItem orderItem : orderItemList) {
            skuIdList.add(orderItem.getSkuId());
        }
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }

        Map<Long, BigDecimal> skuPriceMap = skuPriceListResult.getData().stream()
                .collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        StringBuffer skuPriceString = new StringBuffer();
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuPriceMap.get(orderItem.getSkuId())) != 0) {
                skuPriceString.append(orderItem.getSkuName() + "价格变了;");
            }
        }

        Long orderId = null;
        if (!isBuy) {
            //todo:检查库存是否充足
            //创建订单,保存订单信息,设计到三个表,order_info,order_item.order_log
            try {
                //4 下单
                orderId = this.saveOrder(orderForm);
            } catch (Exception e) {
                e.printStackTrace();
                //抛出异常
                throw new ServiceException("下单失败");
            }
            //将订单中的商品信息从购物车中删除
            remoteCartService.deleteCart(skuIdList, SecurityConstants.INNER);
            return orderId;
        } else {
            try {
                //4 下单
                orderId = this.saveOrder(orderForm);
            } catch (Exception e) {
                e.printStackTrace();
                //抛出异常
                throw new ServiceException("下单失败");
            }


            //返回订单id
            return orderId;
        }


    }

    @Override
    public Map<String, Object> getOneTrade(Long userId, Long skuId) {
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);

        BigDecimal totalAmount = productSku.getSalePrice();
        String tradeNo = this.generateTradeNo(userId);

        Map<String, Object> data = new HashMap();
        data.put("totalAmount", totalAmount);
        data.put("tradeNo", tradeNo);
        data.put("orderItemList", orderItemList);
        data.put("isBuy", true);

        return data;
    }

    @Override
    public List<OrderInfo> getOrderInfoList(Long userId, Integer orderStatus) {
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(
                new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getUserId, userId)
                        .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                        .orderBy(true,false, OrderInfo::getCreateTime));
        if (!CollectionUtils.isEmpty(orderInfoList)) {
            List<Long> orderIds = orderInfoList.stream().map(orderInfo -> orderInfo.getId()).collect(Collectors.toList());
            List<OrderItem> orderItemList = orderItemMapper.selectList(
                    new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIds));
            Map<Long, List<OrderItem>> groupByOrderId = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(groupByOrderId.get(orderInfo.getId()));
            }
//            Collections.sort(orderInfoList, (orderInfo1, orderInfo2) -> orderInfo2.getCreateTime().compareTo(orderInfo1.getCreateTime()));
        }

        return orderInfoList;
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderId));
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm) {
        //保存order_info
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setOrderNo(orderForm.getTradeNo());
        //计算金额
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        orderInfo.setOrderStatus(0);
        orderInfo.setRemark(orderForm.getRemark());

        //设置收货信息
        R<UserAddress> userAddressResult = remoteUserAddressService.getInfo(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode()) {
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        orderInfoMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();

        //保存order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderId);
        }
        orderItemService.saveBatch(orderItemList);

        //保存order_log
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(0L);
        orderLog.setNote("提交订单");
        orderlogMapper.insert(orderLog);

        return orderId;

    }

    /**
     * 生成流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 校验流水号
     *
     * @param userId
     * @param tradeNo
     * @return
     */
    private Boolean checkTradeNo(Long userId, String tradeNo) {
        String tradeNoKey = generateTradeNo(userId);
        String cacheTradeNo = (String) redisTemplate.opsForValue().get(tradeNoKey);
        return tradeNo.equals(cacheTradeNo);
    }

    private void deleteTradeNo(Long userId) {
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }
}